import React from 'react';

export class Rating extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      rating: props.value,
      hoverAt: null,
    };
  }

  static getDerivedStateFromProps = (nextProps, prevState) => {
    if (prevState.rating !== nextProps.value) {
      return {
        rating: nextProps.value,
        hoverAt: prevState.hoverAt,
      };
    }
    return null;
  }

  handleMouseOver = (idx) => {
    this.setState({
      hoverAt: idx + 1,
    });
  }

  handleMouseOut = () => {
    this.setState({
      hoverAt: null,
    });
  }

  handleClick = (idx) => {
    this.setState({
      rating: idx + 1,
    });
  }

  render() {
    const { onClick, id } = this.props;
    const { hoverAt, rating } = this.state;

    return (
      <div>
        <p>
          Rating:
        </p>
        {
          [0, 1, 2, 3, 4].map(i => (
            <span
              onMouseOver={() => this.handleMouseOver(i)}
              onFocus={() => this.handleMouseOver(i)}
              onMouseOut={() => this.handleMouseOut()}
              onBlur={() => this.handleMouseOut()}
              onClick={() => {
                this.handleClick(i);
                onClick({ value: i + 1 });
              }}
              key={`${id}_${i}`}
              role="presentation"
            >
              {i < (hoverAt || rating) ? '\u2605' : '\u2606'}
            </span>
          ))
        }
      </div>
    );
  }
}
